package cn.com.gift.utils;

import cn.com.gift.dto.LoginUserInfo;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Copyright (C), 2018-2023
 * FileName: GlobalVariable
 * Author:   Mr
 * Date:     2023/4/9 15:14
 * Description:
 */
public class GlobalVariable {

    private static Map<String, LoginUserInfo> loginInfo = new ConcurrentHashMap<>();

    public static LoginUserInfo getLoginUser(HttpServletRequest request) {
        return loginInfo.get(getIPAddress(request));
    }

    public static void removeLoginUser(HttpServletRequest request) {
        loginInfo.remove(getIPAddress(request));
    }

    public static void putLoginUser(HttpServletRequest request, LoginUserInfo loginUser) {
        loginInfo.put(getIPAddress(request),loginUser);
    }

    public static String enPassword(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
    }

    public static String getIPAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }

    public static void main(String[] args) {
        System.out.println(enPassword("1qaz@WSX"));
    }
}
